import { notification, message } from 'antd';
import lodash from 'lodash';
import request from 'axios';
import { uuid } from './utils';
import crypto from 'crypto-js';
import { Base64 } from 'js-base64';
function computeSignature(accessKeySecret, canonicalString) {
  return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

function getFormDataParams({ policyType }) {
  const type = {
    image: 'image',
    file: 'file',
    video: 'video',
  }[policyType];
  const date = new Date();
  date.setHours(date.getHours() + 1);
  const policyText = {
    expiration: date.toISOString(), // 设置policy过期时间。
    conditions: [
      // 限制上传大小。
      ['content-length-range', 0, 1024 * 1024 * 1024],
    ],
  };
  const policy = Base64.encode(JSON.stringify(policyText)); // policy必须为base64的string。
  const accessKeyId = 'LTAI5tR86sf7KBXGL8JJKTAV';
  const accessKeySecret = 'wEJfn88geGEluuDebx0zqhU67STLOw';
  const signature = computeSignature(accessKeySecret, policy);
  const formData = {
    OSSAccessKeyId: accessKeyId,
    signature,
    policy,
    host: 'https://resource.gy.cn/',
    bucket: 'gygj-resource',
    folder: type,
    success_action_status: 200,
  };
  return formData;
}
/**
 * oss 文件上传
 * @param {*} file 文件数据 File Blob string | File[] Blob[] string[] | { file:UploadFile, fileList: object[] }
 * 本地文件流数组          | 单文件    | 路径( 字符串 | 数组 )（原样即刻返回）                     | upload组件数据
 * [File[100],File[100]] | File[100] | 'http://img.com' | ['http://img.com','http://img.com'] | {file:File[100], fileList: [{originFileObj:File[100]},{originFileObj:File[100]}]}
 * @param fieldNames 对象别名 默认upload原始数据字段 { listKey = 'fileList', originFileObj = 'originFileObj', url = 'url' }
 * @param policyType oss凭证获取类型 string image上传图片
 * @param ossType oss执行操作类型 string put上传
 * @param {*} return 返回Promise对象 array 按顺序返回文件url数组
 */

//  错误提醒
const notificationInfo = (info) => {
  message.destroy();
  notification.info({
    message: '温馨提示',
    description: info,
  });
  return new Promise((reject) => reject('error'));
};

// 获取oss凭证
const fetchGetOssPolicy = async ({ policyType = 'image' }) => {
  // 上传类型
  return async (file) => {
    console.log(data);
    const data = getFormDataParams({ policyType });
    const { host, folder, bucket, policy, signature, OSSAccessKeyId } = data;
    // 设置路径 + 文件名 + 文件后缀
    console.log(file['name'], 123123)
    let _fileRath = `${folder}/${uuid()}${file['name'] !== 'undefined' ? file['name'].replace(/.+\./, '.') : '.png'
      }`;
    const formData = new FormData();
    formData.append('key', _fileRath);
    Object.keys(data).forEach((item) => {
      formData.append(item, data[item]);
    });
    formData.append('file', file);
    request.defaults.withCredentials = false;
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    };
    let putres = await request.post(host, formData, config);
    const { status } = putres;
    if (status === 200) {
      return host + _fileRath;
    } else {
      message.destroy();
      return false;
    }
  };
};

// 上传文件
const aliOssUpload = async (file = '', fieldNames = {}, policyType = 'image', ossType = 'put') => {
  if (!file) return new Promise((resolve) => resolve(''));
  // file 默认是数组直接赋值
  let fileDataArray = file || [];

  // 预处理file数据 无论如何 处理成数组形式
  if (ossType === 'put') {
    if (typeof file === 'string') {
      message.destroy();
      // file 是字符串直接返回 （已经上传的文件生成了http信息）
      message.destroy();
      return new Promise((resolve) => resolve(file));
    } else if (file instanceof Blob || file instanceof File) {
      // file 是单个文件 File[100]
      fileDataArray = [file];
    } else if (lodash.isPlainObject(file)) {
      // file 是原始对象 {file:File[100], fileList: [{url:'http://img.com'},{originFileObj:File[100]}]}
      const { listKey = 'fileList', originFileObj = 'originFileObj', url = 'url' } = fieldNames;
      fileDataArray = file[listKey].map((item) => item[originFileObj] || item[url]);
    }
  }

  message.loading('文件保存中......', 0);
  // 向后台获取oss凭证 后上传文件
  const osshandle = await fetchGetOssPolicy({ policyType, ossType });
  // 最后返回文件url数组
  const fileUrlArray = [];
  // 文件数组遍历
  for (const item_1 of fileDataArray) {
    if (typeof item_1 === 'string') {
      fileUrlArray.push(item_1);
    } else {
      await osshandle(item_1).then((res) => {
        if (!res) {
          notificationInfo('文件上传失败');
          return;
        }
        fileUrlArray.push(res);
      });
    }
  }
  message.destroy();
  return fileUrlArray;
};

export default aliOssUpload;
